<template>
  <div class="progress-bar" @click="onClick">
    <div class="bar-inner">
      <!-- 当前进度条 -->
      <div class="progress" ref='progress' :style="progressStyle"></div>
      <div class="progress-btn-wrapper">
        <div class="progress-btn" :style='btnStyle' @touchstart='onTouchStart' @touchmove="onTouchMove" @touchend="onTouchEnd"></div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'progress-bar',
  props: {
    // 当前进度
    progress: {
      type: Number,
      default: 0
    }
  },
  data () {
    return {
      offset: 0 // 偏移量
    }
  },
  computed: {
    btnStyle() {
      return `transform:translate(${this.offset}px, 0)`
    },
    progressStyle() {
      return `width:${this.offset}px`
    }
  },

  watch: {
    progress(newProgress) {
      const barWidth = (this.$el.clientWidth - 16) * newProgress
      this.offset = barWidth
    }
  },
  mounted() {
    this.touch = {}
  },
  methods: {
    onTouchStart(e) {
      this.touch.x1 = e.touches[0].pageX
      // 获取开始位置
      this.touch.beginWidth = this.$refs.progress.clientWidth
    },
    onTouchMove(e) {
      // 移动的位置
      const delta = e.touches[0].pageX - this.touch.x1
      // 位移过后的一个宽度
      const tempWidth = this.touch.beginWidth + delta
      // 获取进度条的实际宽度
      const barWidth = this.$el.clientWidth - 16
      // 修改后  边界限制在0和1之间
      const progress = Math.min(1, Math.max(tempWidth / barWidth, 0))
      this.offset = barWidth * progress
      this.$emit('progress-changing', progress)
    },
    onTouchEnd() {
      const barWidth = this.$el.clientWidth - 16
      const progress = this.$refs.progress.clientWidth / barWidth
      this.$emit('progress-changed', progress)
    },

    onClick(e) {
      // 获取最左边坐标
      const rect = this.$el.getBoundingClientRect()
      // 当前点击的位置宽度 减去初始距离html左边的宽度
      const offsetWidth = e.pageX - rect.left
      const barWidth = this.$el.clientWidth - 16
      const progress = offsetWidth / barWidth
      this.$emit('progress-changed', progress)
    }
  }
}
</script>

<style scoped lang='scss'>
 .progress-bar {
    height: 30px;
    .bar-inner {
      position: relative;
      top: 13px;
      height: 4px;
      background: rgba(0, 0, 0, 0.3);
      .progress {
        position: absolute;
        height: 100%;
        background: $color-theme;
      }
      .progress-btn-wrapper {
        position: absolute;
        left: -8px;
        top: -13px;
        width: 30px;
        height: 30px;
        .progress-btn {
          position: relative;
          top: 7px;
          left: 7px;
          box-sizing: border-box;
          width: 16px;
          height: 16px;
          border: 3px solid $color-text;
          border-radius: 50%;
          background: $color-theme;
        }
      }
    }
  }
</style>
